package com.imooc.servlet;

import com.imooc.bean.Command;
import com.imooc.bean.CommandContent;
import com.imooc.service.CommandService;
import com.imooc.service.MessageService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Random;

/**
 *  指令Servlet
 *  这里没有做微信页面, 直接调用接口
 */
public class CommandServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码
        request.setCharacterEncoding("utf-8");
        // 接收传入参数的值
        String name = request.getParameter("name");
        String description = request.getParameter("description");
        // 向页面传值
        request.setAttribute("name", name);
        request.setAttribute("description", description);
        // 查询消息列表并传回页面
        CommandService commandService = new CommandService();
        List<Command> commandList = commandService.queryCommandList(name,description);
        String html = "<div style='color:red'>Null</div>";
        if (commandList.size() > 0 ) {
            List<CommandContent> contentList = commandList.get(0).getContentList();
            CommandContent commandContent =  contentList.get(new Random().nextInt(contentList.size()));
            request.setAttribute("content", commandContent.getContent());
            html = "<div style='color:green'>" + commandContent.getContent() + "</div>";
        }
        // 向页面跳转
        //request.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(request,response);
        // 页面打印结果
        response.setContentType("text/html; charset=UTF-8");
        //response.setCharacterEncoding("utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.println(html);
    }
}
